package band.wukong.practice.javase.core.io.stream.filterstream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.PrintStream;

/**
 * Desc:
 * Author: sunjs
 * Date: 2009-11-16 14:08:09
 */
public class TestPrintStream {
    public static void main(String[] args) throws Exception {
//        test01()
//        test02();
        test03();
    }

    public static void test01() {
        PrintStream out = new PrintStream(System.out);

        out.println("生如夏花");

        out.print("生如夏花");
        out.println();

        out.print("生如夏花\n");

        //三段代码效果相同
    }

    public static void test02() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(out, true);
        ps.print("道");
        ps.close();

        byte[] buff = out.toByteArray();
        System.out.println("采用本地操作系统的默认字符编码：");
        readBuff(buff);

        out = new ByteArrayOutputStream();
        DataOutputStream ds = new DataOutputStream(out);
        ds.writeUTF("道");
        ds.close();

        buff = out.toByteArray();
        System.out.println("采用使用Java语言的UTF-8字符编码：");
        readBuff(buff);
    }

    public static void test03() {
        PrintStream out = new PrintStream(System.out, true);    //true表示
        out.println("生如夏花");
        /*
            PrintStream和BufferedOutputStream一样带有缓冲区。两者的区别在于：
            Buffered只有在缓冲区满的时候，才会自动执行物理写数据的操作；Print可以让用户来决定缓冲策略。

            默认情况下，PrintStream也只有在缓冲区满的时候，才会自动flush。
            如果构造方法中参数autoFlush为true，则表示在以下情况也会自动把缓冲区的数据写到输出流:
            1.输出一个字节数组
            2.输出一个换行符
            3.执行了println()方法
         */

    }

    private static void readBuff(byte[] buff) throws Exception {
        ByteArrayInputStream in = new ByteArrayInputStream(buff);
        int data;
        while ((data = in.read()) != -1) {
            System.out.println(data + " ");
        }
        System.out.println();
        in.close();
    }
}
